import { Detail } from './detail-model.js';
import { Order } from '../orderOk/order-model.js';
import { Token } from '../../utils/token.js';
const app = getApp();
var token = new Token();
var WxParse = require('../../wxParse/wxParse.js');
var order = new Order();
var detail = new Detail();
Page({
  data: {
    indicatorDots: true,
    autoplay: false,
    interval: 3000,
    tabIndex: 0,
    showTop: false,
    goodsObj: {},
    modalOpened: false,//模态框
    showParams: {},
    g_num: 1,
    goods_spec_arr: [], // 记录规格的数组
    specData: [],
  },
  onLoad(options) {
    var that = this;
    app.userLogin(app.globalData.shopid);
    this.setData({
      uid:app.globalData.uid
    })
    that._loadData(options);
  },
  onShow() {

  },
  //私有的方法
  _loadData: function (options) {
    let that = this;
    detail.getProductDetailByID(options.id, (data) => {
      if (data.data.detail.spec_type == 20) {
        that.initManySpecData(data.data);
      } else {
        that.setData(
          {
            goods_sku_id: data.data.detail.spec[0].spec_sku_id,
            goods_price: data.data.detail.spec[0],
            stock_num: data.data.detail.spec[0].stock_num,
            service_price: data.detail.service_price,
            official_price: data.detail.official_price,
            goods_unit: data.detail.goods_unit,
            goodsname: data.detail.goods_name,
            imgs_url: data.detail.imgs_url
          }
        );
      }
      var content = data.data.detail.content;
      WxParse.wxParse('content', 'html', content, this, 5);
      if (data.data.detail.spec_type === '20') {
        that.make_sku_showData(data.data.specData, 0);
        that.showSelectSpec(data.data.specData);
      }
      that.setData(
        {
          detail: data.data.detail,
          specData: data.data.specData,
          goods_spec_arr: that.data.goods_spec_arr,
        }
      );

    })
  },
  //规格数据显示
  showSelectSpec: function (data) {
    var Showskuiteam = data.spec_attr;
    var Nowselect = this.data.goods_spec_arr;
    var params = [];
    Showskuiteam.forEach(function (value, index, array) {
      value.spec_items.forEach(function (value1, index1, array1) {
        for (var i = 0; i < Nowselect.length; i++) {
          if (Nowselect[i] == value1.item_id) {
            params.push(value1.spec_value);
          }
        }
      });
    });
    this.setData({
      params: params
    })


  },

  //显示多规格信息
  make_sku_showData: function (data, break_num) {
    var that = this;
    var Showskuiteam = data.spec_attr;
    var Nowselect = this.data.goods_spec_arr;
    Showskuiteam.forEach(function (value, index, array) {
      value.spec_items.forEach(function (value1, index1, array1) {
        var status = 0;
        for (var i = 0; i < Nowselect.length; i++) {
          if (Nowselect[i] == value1.item_id) {
            status = 1;
            value1.isActive = true;
          }
        }
        if (status == 0) {
          value1.isActive = false;
        }
      });
    });

  },

  //初始化商品多规格信息
  initManySpecData: function (data) {
    var that = this;
    for (let i in data.specData.spec_list) {
      if (data.specData.spec_list[i].form.stock_num >= 0) {
        var sku_id = data.specData.spec_list[i].spec_sku_id.split('_');
        that.setData({
          goods_sku_id: data.detail.spec[i].spec_sku_id,
          goods_price: parseInt(data.detail.spec[i].goods_price/31),
          stock_num: data.detail.spec[i].stock_num,
          service_price: data.detail.service_price,
          official_price: data.detail.official_price,
          goods_unit: data.detail.goods_unit,
          goodsname: data.detail.goods_name,
          imgs_url: data.detail.imgs_url,
          spec_image: data.detail.spec[i].spec_image,
        });
        for (let j in sku_id) {
          that.data.goods_spec_arr[j] = parseInt(sku_id[j]);
        }
        break;

      }
    }
  },
  //规格选中
  selectParam(event) {
    let goods_spec_arr = this.data.goods_spec_arr;
    goods_spec_arr[event.currentTarget.dataset.attr_idx] = parseInt(event.currentTarget.id);
    this.make_good_sel_sku(goods_spec_arr, event.currentTarget.dataset.attr_idx);
    this.updateSpecGoods();
    this.make_sku_showData(this.data.specData, event.currentTarget.dataset.attr_idx);
    this.showSelectSpec(this.data.specData);
    this.setData({
      specData: this.data.specData,
    });
  },
  /** 更新商品规格信息  */
  updateSpecGoods: function () {
    let spec_sku_id = this.data.goods_spec_arr.join('_');
    let spec_list = this.data.specData.spec_list,
      skuItem = spec_list.find((val) => {
        return val.spec_sku_id == spec_sku_id;
      });
    if (typeof skuItem === 'object') {
      this.setData({
        goods_sku_id: skuItem.spec_sku_id,
        goods_price: parseInt(skuItem.form.goods_price/31),
        stock_num: skuItem.form.stock_num,
        spec_image: skuItem.form.spec_image
      });
    }
  },
  //组合商品规格数据
  make_good_sel_sku: function (goods_spec_arr, attr_idx) {
    var that = this;
    var spec_list = this.data.specData.spec_list;
    spec_list.forEach(function (value, index, array) {

      if (value.form.stock_num >= 0) {
        var sku_id_arr = value.spec_sku_id.split('_');
        sku_id_arr.forEach(function (sku_id_arrvalue, sku_id_arrindex, sku_id_arrarray) {
         
        })
      }
    });

    //格式化
    goods_spec_arr.forEach(function (value, index, array) {
      goods_spec_arr[index] = parseInt(value);
    });
    that.setData({
      goods_spec_arr: goods_spec_arr,
    });
  },
  // 意外保障服务说明
  showExplain() {
    this.setData({
      modalOpened: true,
    });
  },
  onModalClose() {
    this.setData({
      modalOpened: false,
    });
  },
  // 商品说明，规格参数切换
  changeTab(e) {
    this.setData({
      tabIndex: e.target.dataset.index
    })
  },
  // 选择参数后确定
  paramOk() {
    var params = {
      sku_id: this.data.goods_sku_id,
      goods_id: this.data.detail.goods_id,
      margin: this.data.detail.margin_price, //押金
      service_price: this.data.service_price, //增值服务费用
      mouth:this.data.params.length>2?parseInt(this.data.params[2]):parseInt(this.data.params[1]), //月份
      number: this.data.g_num,
      user_id:app.globalData.uid
    };
    order.isInRent(app.globalData.uid,(data) => {
      if (data.code == 0) {
        my.showToast({
          type: 'fail',
          content: "有未履约完的订单,不能再次下单",
          success: (res) => {
            my.switchTab({
              url: '/pages/index/index',
            });
          },
        });
      } else if (data.code == 1) {
        order.doOrder(params, (data) => {
          //  my.navigateTo({
          //       url: '/pages/orderOk/orderOk?id=' + data.data.order_id
          //     });
          this.face(data.data.order_no, data.data.order_id);
          
        })
      }
     
    })
  },

  //刷脸认证
  face: function (bizId, order_id) {
    my.ap.faceVerify({
      bizId: bizId,
      bizType: '2',
      success: (res) => {
        if (res.faceRetCode == 1000 && res.retCode =='OK_SUCCESS') {
          //表示刷脸成功接着要进入服务端进行验证
          var params = {
            biz_id: bizId,
            zim_id: res.zimId,
            face_type: '2',
            bizType: 2,
          };
          this.faceService(params, order_id);
        }else if(res.faceRetCode==1001){
          my.showToast({
          type: 'fail',
          content:'系统错误',
        });
        }else if(faceRetCode ==1003)
        {
           my.showToast({
          type: 'fail',
          content: "验证中断",
        });
        }else if(faceRetCode==2002)
        {
           my.showToast({
          type: 'fail',
          content: "网络错误",
          });
        }else{
           my.showToast({
          type: 'fail',
          content: "刷脸失败",
          });
        }
      }
    })
  },

  //刷脸服务端认证
  faceService: function (params, order_id) {
    order.faceNotify(params, (data) => {
      var info = data.data.zoloz_identification_customer_certifyzhub_query_response;
      if (info.code == 10000) {
        //表示认证成功接下来走资金预授权
        this.freeAuth(order_id);
      }else if(info.code ==40004)
      {
        if(info.sub_code=='SYSTEM_ERROR')
        {
          my.showToast({
          type: 'fail',
          content: "系统繁忙请稍后再试",
          });
        }
        if(info.sub_code=='INVALID_ARGUMENT')
        {
          my.showToast({
          type: 'fail',
          content: "请求参数无效",
          });
        }
        if(info.sub_code=='NOT_SAME_PERSON')
        {
          my.showToast({
          type: 'fail',
          content: "不是本人",
          });
        }
        
      }
    })
  },

  //资金预授权
  freeAuth(order_id) {
    order.orderFree(order_id, (data) => {
      //小程序唤起冻结
      my.tradePay({
        orderStr: data.data,
        success: (res) => {
          if(res.resultCode ==6001)
          {
            my.showToast({
              type:'fail',
              content:'你已取消'
            })
          }else{
             var params = JSON.parse(res.result);
             order.freeBack(params, (res) => {
            if (res.code == 1 && res.data) {
              my.navigateTo({
                url: '/pages/orderOk/orderOk?id=' + order_id
              });
            }else{
              my.showToast({
                type:'fail',
                content:'接口错误',
              });
            }
          })
          }
        },
      });
    })

  },
  // 立即租赁
  onTopBtnTap() {
    this.setData({
      showTop: true,
    });
  },
  // 关闭参数的选择
  onPopupClose() {
    this.setData({
      showTop: false,
    });
  },
  //如果存在shopid就将shopID写进会员表中
  updateUserInfo(shopid) {
    detail.updateUserInfo(shopid, (data) => {

    })
  }

});
